package com.example.security.service.impl;

import com.example.security.entity.SysUser;
import com.example.security.exception.BusinessException;
import com.example.security.mapper.SysPermissionMapper;
import com.example.security.mapper.SysUserMapper;
import com.example.security.service.SecurityService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SecurityServiceImpl implements SecurityService {

    private final SysPermissionMapper permissionMapper;
    private final SysUserMapper userMapper;

    @Override
    public SysUser getCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                throw new BusinessException("用户未登录");
            }
            return (SysUser) authentication.getPrincipal();
        } catch (Exception e) {
            throw new BusinessException("获取用户信息异常", e);
        }
    }

    @Override
    public boolean isAdmin(SysUser user) {
        return user != null && user.isAdmin();
    }

    @Override
    public boolean isAdminById(Long userId) {
        SysUser user = userMapper.selectById(userId);
        return isAdmin(user);
    }

    @Override
    public boolean hasPermission(Long userId, String permission) {
        // 系统管理员拥有所有权限
        if (isAdminById(userId)) {
            return true;
        }
        
        // 查询用户权限列表
        List<String> permissions = permissionMapper.selectPermissionsByUserId(userId);
        return permissions.contains(permission);
    }
} 